package com.zjw.zy.base.special;

import androidx.annotation.NonNull;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/10/10 9:37
 * <p>
 * 请求的队列
 */
public final class PCMessageQueue<T> {


    private final Queue<T> mMessageQueue = new LinkedList<>();
    private final Map<T, Runnable> mConsumeMap = new HashMap<>();

    public PCMessageQueue() {

    }


    public T produce(@NonNull T message) {
        synchronized (this) {
            mMessageQueue.offer(message);
            return message;
        }
    }

    public void consume(T message, Runnable task) {
        synchronized (this) {
            mConsumeMap.put(message, task);

            next();
        }
    }

    public void remove(T message) {
        synchronized (this) {
            mMessageQueue.removeIf(id -> id.equals(message));
        }
    }

    private void next() {
        T message = mMessageQueue.peek();
        if (message == null) {
            return;
        }

        for (T itemMessage : mConsumeMap.keySet()) {
            if (!message.equals(itemMessage)) {
                continue;
            }

            Runnable task = mConsumeMap.remove(itemMessage);
            if (task != null) {
                try {
                    task.run();
                } catch (Exception ignore) {

                }
            }
            //出队
            mMessageQueue.poll();
            next();
            return;
        }
    }
}
